package com.example.library;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputLayout;
import com.example.library.util.LocalStorageManager;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private EditText etId, etPassword;
    private AutoCompleteTextView spUserType;
    private CheckBox cbRemember;
    private MaterialButton btnLogin, btnRegister;
    private SharedPreferences sharedPreferences;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etId = findViewById(R.id.et_id);
        etPassword = findViewById(R.id.et_password);
        spUserType = findViewById(R.id.sp_user_type);
        cbRemember = findViewById(R.id.cb_remember);
        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);
        progressBar = findViewById(R.id.progress_bar);

        // 设置用户类型下拉列表
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.user_types, android.R.layout.simple_dropdown_item_1line);
        spUserType.setAdapter(adapter);
        spUserType.setText(adapter.getItem(0).toString(), false); // 默认选择第一项（学生）

        sharedPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
        loadSavedLogin();

        btnLogin.setOnClickListener(v -> {
            String id = etId.getText().toString();
            String password = etPassword.getText().toString();
            String userType = spUserType.getText().toString();
            boolean remember = cbRemember.isChecked();

            if (TextUtils.isEmpty(id) || TextUtils.isEmpty(password)) {
                Toast.makeText(this, "请输入账号和密码", Toast.LENGTH_SHORT).show();
                return;
            }

            // 保存登录信息（如果选择了记住密码）
            if (remember) {
                saveLogin(id, password, userType);
            } else {
                clearSavedLogin();
            }

            // 显示加载进度条
            progressBar.setVisibility(View.VISIBLE);
            btnLogin.setEnabled(false);

            // 调用API进行登录
            ApiService.getInstance().login(id, password, userType, new ApiService.Callback() {
                @Override
                public void onSuccess(String result) {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        btnLogin.setEnabled(true);
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                        // 保存userId和昵称到LocalStorageManager
                        LocalStorageManager localStorageManager = new LocalStorageManager(LoginActivity.this);
                        String nickname = "管理员";
                        if (userType.equals("学生")) {
                            nickname = "学生";
                        }
                        localStorageManager.saveUserData(id, nickname);

                        // 根据用户类型跳转到相应的主界面
                        Intent intent;
                        if ("学生".equals(userType)) {
                            Log.d(TAG, "Logging in as student");
                            intent = new Intent(LoginActivity.this, StudentMainActivity.class);
                            intent.putExtra("isAdmin", false);
                        } else {
                            Log.d(TAG, "Logging in as admin");
                            intent = new Intent(LoginActivity.this, AdminMainActivity.class);
                            intent.putExtra("isAdmin", true);
                        }
                        startActivity(intent);
                        finish();
                    });
                }

                @Override
                public void onFailure(String error) {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        btnLogin.setEnabled(true);
                        Toast.makeText(LoginActivity.this, "登录失败: " + error, Toast.LENGTH_SHORT).show();
                    });
                }
            });
        });

        btnRegister.setOnClickListener(v -> {
            startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
        });
    }

    private void saveLogin(String id, String password, String userType) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("id", id);
        editor.putString("password", password);
        editor.putString("userType", userType);
        editor.putBoolean("remember", true);
        editor.apply();
    }

    private void loadSavedLogin() {
        boolean remember = sharedPreferences.getBoolean("remember", false);
        if (remember) {
            etId.setText(sharedPreferences.getString("id", ""));
            etPassword.setText(sharedPreferences.getString("password", ""));
            String userType = sharedPreferences.getString("userType", "学生");
            spUserType.setText(userType, false);
            cbRemember.setChecked(true);
        }
    }

    private void clearSavedLogin() {
        sharedPreferences.edit().clear().apply();
    }
} 